package code

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic"
)

type Elastic struct {
	Client *elastic.Client
}

func NewElastic(url string) (es *Elastic, err error) {
	es = &Elastic{}
	es.Client, err = elastic.NewClient(elastic.SetURL(url))
	return
}

//创建数据
func (this *Elastic) Create(index, doc, id string, data interface{}) (err error) {
	var datas []byte
	if datas, err = json.Marshal(data); err != nil {
		return
	}

	if _, err = this.Client.Index().Index(index).Type(doc).Id(id).BodyJson(string(datas)).Do(context.Background()); err != nil {
		return
	}

	return
}

//修改数据
func (this *Elastic) Update(index, doc, id string, data interface{}) (err error) {

	if _, err = this.Client.Update().Index(index).Type(doc).Id(id).Doc(data).Do(context.Background()); err != nil {
		return
	}

	return
}

//查找数据
func (this *Elastic) GetById(index, doc, id string, data interface{}) (err error) {
	var get *elastic.GetResult
	if get, err = this.Client.Get().Index(index).Type(doc).Id(id).Do(context.Background()); err != nil {
		return
	}

	if get.Source != nil && data != nil {
		if err = json.Unmarshal(*get.Source, data); err != nil {
			return
		}
	}

	return
}

//删除数据
func (this *Elastic) DeleteById(index, doc, id string) (err error) {
	_, err = this.Client.Delete().Index(index).Type(doc).Id(id).Do(context.Background())
	return
}
